from urllib import request

import jwt
from datetime import datetime, timedelta
import uuid
from fastapi import FastAPI, Request
from pydantic import BaseModel
from sqlalchemy import and_, or_

from config import SessionLocal
from task import Task, TaskObj, TaskUuid, TaskCreate
from user import User, UserObj, UserUuid, UserCreate, login

app = FastAPI()
# 定义 JWT 秘钥
SECRET_KEY = "skyformCloud"
ALGORITHM = "HS256"


def generate_uuid32():
    return uuid.uuid4().hex[:32]
def getLoginJwt(name: str,uuid: str):
    # 添加载荷数据
    payload = {
        'sub': uuid,
        'name': name,
        'iat': datetime.utcnow(),
        'exp': datetime.utcnow() + timedelta(days=7)  # 过期时间
    }

    # 生成 JWT
    jwt_token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
    return jwt_token

class page(BaseModel):
    pageNum: int
    pageSize: int
    name: str
    status: str

@app.get("/task/{uuid}")
def read_users(uuid: str):
    with SessionLocal() as db:
        task = db.query(Task).filter(Task.uuid == uuid).first()
        return task#JSONResponse(content={"task": task}, media_type="application/json")

# 定义 POST 接口
@app.post("/user/create", response_model=None)
async def create_user(t: UserCreate):
    print(t)
    date_format_with_time = "%Y-%m-%d %H:%M:%S"
    date_create_time = datetime.now()
    date_update_time = datetime.now()
    userUuid = generate_uuid32()
    cname = 'admin'
    obj = User(uuid=userUuid, name=t.name, password=t.password, email=t.email, create_by=cname, create_time=date_create_time, update_by=cname, update_time=date_update_time)
    with SessionLocal() as db:
        users =  db.query(User).filter(or_(User.name == t.name, User.email == t.email)).all()
        if len(users) > 0:
            db.commit()
            return {"code": 500, "msg": "用户名或邮箱已存在"}

        db.add(obj)
        db.commit()
        db.refresh(obj)
        #return user
    # 返回一个 JSON 响应
    return {"code":200,"msg":"success","retObj":t}
@app.post("/user/update", response_model=UserObj)
async def update_user(t: UserObj):
    print(t)
    date_format_with_time = "%Y-%m-%d %H:%M:%S"
    date_create_time = datetime.now()
    date_update_time = datetime.now()

    obj = User(uuid=t.uuid, name=t.name, password=t.password, email=t.email,  create_by=t.create_by, create_time=date_create_time, update_by=t.update_by, update_time=date_update_time)
    with SessionLocal() as db:
        db.merge(obj)
        db.commit()
        #return user
    # 返回一个 JSON 响应
    return t
@app.post("/user/delate", response_model=UserUuid)
async def delate_user(t: UserUuid):
    print(t)

    with SessionLocal() as db:
        user = db.query(User).filter(User.uuid == t.uuid).first()
        if user:
            db.delete(user)
            db.commit()
        #return user
    # 返回一个 JSON 响应
    return t
@app.post("/login", response_model=None)
async def loginSystem(t: login):
    print(t)
    with SessionLocal() as db:
        user = db.query(User).filter(and_(User.name == t.name , User.password == t.password)).first()
        db.commit()
        if user:
            token = getLoginJwt(user.name,user.uuid)
            data = {
                "name": user.name,
                "email": user.email,
                "uuid": user.uuid
            }
            obj = {
                "token":token,
                "user":data
            }
            return {"code":200,"msg":"success","retObj":obj}
        return {"code":401,"msg":"用户密码错误","retObj":''}
        #return user
    # 返回一个 JSON 响应
@app.post("/task/listPage", response_model=None)
async def listPage_task(p: page, request: Request):
    print(p)
    header_data = request.headers
    authorization = header_data.get("Authorization")
    print(authorization)
    if authorization == '':
        return {"code":401,"msg":"error"}
    offset = (p.pageNum -1) * p.pageSize
    #if p.end_time:
    #    date_format_with_time = "%Y-%m-%d %H:%M:%S"
    #    date_end_time = datetime.strptime(p.end_time, "%Y-%m-%d %H:%M:%S").timestamp()
    with SessionLocal() as db:
        #
        query = db.query(Task)
        if p.name:
            query = query.filter(Task.name.like(f"%{p.name}%"))
        if p.status:
            query = query.filter(Task.status == p.status)
        #if p.end_time:
       #     query = query.filter(Task.end_time.timestamp() <= date_end_time)
        total_tasks = query.count()
        tasks = query.offset(offset).limit(p.pageSize).all()
        tasks_json = [task.to_dict() for task in tasks]
        print(tasks_json)
        db.commit()
        #return user
    # 返回一个 JSON 响应
    retObj = {
        "total": total_tasks,
        "data": tasks_json
    }
    return {"code":200,"msg":"success","retObj":retObj}

@app.post("/task/create", response_model=None)
async def create_task(t: TaskCreate, request: Request):
    print(t)
    header_data = request.headers
    authorization = header_data.get("Authorization")
    print(authorization)
    if authorization == '':
        return {"code":401,"msg":"error"}
    date_format_with_time = "%Y-%m-%d %H:%M:%S"
    date_end_time = datetime.strptime(t.end_time, date_format_with_time)
    date_create_time = datetime.now()
    date_update_time = datetime.now()
    taskUuid = generate_uuid32()
    obj = Task(uuid=taskUuid, name=t.name, status=t.status, end_time=date_end_time, user_id=t.user_id, remark=t.remark, create_by=t.create_by, create_time=date_create_time, update_by=t.update_by, update_time=date_update_time)
    with SessionLocal() as db:
        db.add(obj)
        db.commit()
        db.refresh(obj)
        #return user
    # 返回一个 JSON 响应
    retObj = taskUuid
    return {"code":200,"msg":"success","retObj":retObj}
@app.post("/task/update", response_model=None)
async def update_task(t: TaskObj, request: Request):
    print(t)
    header_data = request.headers
    authorization = header_data.get("Authorization")
    print(authorization)
    if authorization == '':
        return {"code":401,"msg":"error"}
    date_format_with_time = "%Y-%m-%d %H:%M:%S"
    date_end_time = datetime.strptime(t.end_time, date_format_with_time)
    date_create_time = datetime.now()
    date_update_time = datetime.now()

    obj = Task(uuid=t.uuid, name=t.name, status=t.status, end_time=date_end_time, user_id=t.user_id, remark=t.remark, create_by=t.create_by, create_time=date_create_time, update_by=t.update_by, update_time=date_update_time)
    with SessionLocal() as db:
        db.merge(obj)
        db.commit()
        #return user
    # 返回一个 JSON 响应
    return {"code":200,"msg":"success","retObj":t}
@app.post("/task/delate", response_model=None)
async def delate_task(t: TaskUuid, request: Request):
    print(t)
    header_data = request.headers
    authorization = header_data.get("Authorization")
    print(authorization)
    if authorization == '':
        return {"code":401,"msg":"error"}

    with SessionLocal() as db:
            task = db.query(Task).filter(Task.uuid == t.uuid).first()
            if task:
                db.delete(task)
                db.commit()
            #return user
        # 返回一个 JSON 响应
    retObj = t.uuid
    return {"code":200,"msg":"success","retObj":retObj}
@app.post("/task/getTask", response_model=None)
async def get_taskByUuid(t: TaskUuid, request: Request):
    print(t)
    header_data = request.headers
    authorization = header_data.get("Authorization")
    print(authorization)
    if authorization == '':
        return {"code":401,"msg":"error"}

    with SessionLocal() as db:
        task = db.query(Task).filter(Task.uuid == t.uuid).first()
        if task:
            taskInfo = task.to_dict()
            db.commit()
        #return user
    # 返回一个 JSON 响应
    retObj = taskInfo
    return {"code":200,"msg":"success","retObj":retObj}


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
